// 云函数入口文件
const cloud = require('wx-server-sdk')
var rp = require('request-promise');
const TcbRouter = require('tcb-router');
cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
	const app = new TcbRouter({
		event
	})
	app.use(async (ctx, next) => {
		ctx.data = {}
		ctx.wxContext = cloud.getWXContext()
		await next()
	})
	app.router('getOpenid', async (ctx, next) => {
		try {
			ctx.body = ctx.wxContext.OPENID
		} catch (err) {
			ctx.body = false
		}
	})
	app.router('getPhone', async (ctx, next) => {
		try {
			ctx.body = event.weRunData.data.phoneNumber
		} catch (err) {
			ctx.body = false
		}
	})
	app.router('oneKeyLogin', async (ctx, next) => {
		try {
			if(!event.table) return ctx.body = false
			let res = await db.collection(event.table).where(
			    _.or([{
						phone:event.phone
					},
					{
						_openid: ctx.wxContext.OPENID
					}
				]))
				.get()
			if (res.errMsg == 'collection.get:ok' && res.data.length) {
				ctx.body = res.data[0]
				return;
			}
			event.userInfo._openid = ctx.wxContext.OPENID
			event.userInfo.createTime = Date.now()
			event.userInfo.updateTime = Date.now()
			await db.collection(event.table).add({
				data: event.userInfo
			})
			ctx.body = event.userInfo
		} catch (err) {
			ctx.body = err
		}
	})
	


	return app.serve();

}


